package com.example.jf.jfapp.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.jf.jfapp.R;
import com.facebook.drawee.view.SimpleDraweeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by jf on 2017/7/27.
 */

public class WodeFragment extends Fragment {
    @BindView(R.id.simple)
    SimpleDraweeView simple;
    @BindView(R.id.tv_myName)
    TextView tvMyName;
    @BindView(R.id.tv_personName)
    TextView tvPersonName;
    Unbinder unbinder;
    @BindView(R.id.ll_collect)
    LinearLayout llCollect;
    @BindView(R.id.ll_write)
    LinearLayout llWrite;
    @BindView(R.id.ll_sign)
    LinearLayout llSign;
    @BindView(R.id.ll_message)
    LinearLayout llMessage;
    @BindView(R.id.ll_historic)
    LinearLayout llHistoric;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.ll_ask)
    LinearLayout llAsk;
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.ib)
    ImageButton ib;
    @BindView(R.id.photo)
    TextView photo;
    @BindView(R.id.openAlbum)
    TextView openAlbum;
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    private boolean isLogin;
    private static final String TAG = "WodeFragment";
    private BottomSheetBehavior behavior;
    public static final int TAKE_PHOTO=2;
    private Uri imageUri;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.fragment_my, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

//    @Override
//    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//        super.onViewCreated(view, savedInstanceState);
//        isLogin = AppConfigUtils.getInstance().getLoginStatu(getActivity());
//        if (!isLogin) {
//            llMain.setVisibility(View.VISIBLE);
//            llLogin.setVisibility(View.GONE);
//        }
//        getData();
//        behavior = BottomSheetBehavior.from(llBase);
//        simple.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
//            }
//        });
//        ib.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
//            }
//        });
//    }
//
//    private void getData() {
//        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
//        String userId = AppConfigUtils.getInstance().getLoginInfo(getActivity()).getObjectId();
//        UserResponse userResponse = new UserResponse(userId);
//        Request request = RequestUtils.requestPOST(userResponse, Constant.URL.GETMEINFO);
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                Log.e(TAG, "onResponse: " + result);
//                final UserBean userBean = new Gson().fromJson(result, UserBean.class);
//                if (userBean != null) {
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            simple.setImageURI(userBean.getResult().getAuthor().getHeadProtrait());
//                            tvMyName.setText(userBean.getResult().getAuthor().getUsername());
//                        }
//                    });
//                }
//            }
//        });
//
//    }
//
//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        unbinder.unbind();
//    }
//
//    @OnClick({R.id.ll_share, R.id.ll_ask,R.id.iv_code, R.id.ll_collect, R.id.ll_write, R.id.ll_sign
//            , R.id.ll_message, R.id.ll_historic, R.id.ll_setting, R.id.ll_login, R.id.ll_main
//            , R.id.photo, R.id.openAlbum, R.id.cancel})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.ll_login:
//                startActivity(new Intent(getActivity(), LoginActivity.class));
//                break;
//            case R.id.ll_main:
//                startActivity(new Intent(getActivity(), PersonalActivity.class));
//                break;
//            case R.id.ll_share:
//                startActivity(new Intent(getActivity(), MyShareActivity.class));
//                break;
//            case R.id.ll_ask:
//                startActivity(new Intent(getActivity(), AskActivity.class));
//                break;
//            case R.id.iv_code:
//                //个人二维码展示
//                AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
//                AlertDialog dialog=builder.create();
//                View imgView=View.inflate(getActivity(),R.layout.image_code,null);
//                ImageView iv=imgView.findViewById(R.id.img_show);
//                String content="你好";
//                Bitmap logoBitmap=BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
//                Bitmap bitmap= CodeUtils.createImage(content,400,400,logoBitmap);
//                iv.setImageBitmap(bitmap);
//                Window dialogWindow = dialog.getWindow();
//                WindowManager.LayoutParams lp=dialogWindow.getAttributes();
//                dialogWindow.setGravity(Gravity.CENTER);
//                dialog.setView(imgView);
//                dialog.show();
//                break;
//            case R.id.ll_collect:
//                startActivity(new Intent(getActivity(), CollectActivity.class));
//                break;
//            case R.id.ll_write:
//                startActivity(new Intent(getActivity(), WriteActivity.class));
//                break;
//            case R.id.ll_sign:
//                startActivity(new Intent(getActivity(), SignActvity.class));
//                break;
//            case R.id.ll_message:
//                startActivity(new Intent(getActivity(), MessageActivity.class));
//                break;
//            case R.id.ll_historic:
//                startActivity(new Intent(getActivity(), HistoricActivity.class));
//                break;
//            case R.id.ll_setting:
//                startActivity(new Intent(getActivity(), SettingsActivity.class));
//                break;
//            case R.id.photo:
//                File outImage=new File(getActivity().getExternalCacheDir(),"out_image.jpg");
//                try{
//                    if(outImage.exists()){
//                        outImage.delete();
//                    }
//                    outImage.createNewFile();
//                }catch (IOException e){
//                    e.printStackTrace();
//                }
//                imageUri=Uri.fromFile(outImage);
//                String state= Environment.getExternalStorageState();//获取内存卡可用状态
//                if(state.equals(Environment.MEDIA_MOUNTED)){
//                    //内存卡可用
//                    Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
//                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
//                    startActivityForResult(intent,TAKE_PHOTO);
//                }else {
//                    Toast.makeText(getActivity(), "内存不可用", Toast.LENGTH_SHORT).show();
//                }
//                break;
//            case R.id.openAlbum:
////                Toast.makeText(getActivity(), "你好", Toast.LENGTH_SHORT).show();
//                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
//                } else {
//                    openPic();
//                }
//                break;
//            case R.id.cancel:
//                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
//                break;
//        }
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case 1:
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    openPic();
//                } else {
//                    Toast.makeText(getActivity(), "用户拒绝", Toast.LENGTH_SHORT).show();
//                }
//        }
//    }
//
//    private void openPic() {
//        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, 1);
//    }
//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case 1:
//            if (resultCode == Activity.RESULT_OK && data != null) {
//                Uri selectImage = data.getData();
//                String[] filePathColumns = {MediaStore.Images.Media.DATA};
//                Cursor c = getActivity().getContentResolver().query(selectImage, filePathColumns, null, null, null);
//                c.moveToFirst();
//                int columnIndex = c.getColumnIndex(filePathColumns[0]);
//                String imagePath = c.getString(columnIndex);
////            showImage(imagePath);
//                getPicData(imagePath);
//                c.close();
//            }
//            break;
//            case TAKE_PHOTO:
//                if(resultCode==Activity.RESULT_OK){
//                    try {
//                        Bitmap bitmap= BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
//                        simple.setImageBitmap(bitmap);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                }
//                break;
//        }
//    }
//
//    private void getPicData(String imagePath) {
//        OkHttpClient client = OkHttpUtils.getOkHttpClient();
//        File imageFile = new File(imagePath);
//        MediaType IMAGETYPE = MediaType.parse("image/jpeg");
//        RequestBody body = RequestBody.create(IMAGETYPE, imageFile);
//        Request request = new Request.Builder()
//                .post(body)
//                .addHeader("X-LC-Id", "EkMW81DInN4eoh61yJSuMSIQ-gzGzoHsz")
//                .addHeader("X-LC-Key", "80FiCJK6omszBpfxjjFAmCqo")
//                .addHeader("Content-Type", "image/*")
//                .url("https://api.leancloud.cn/1.1/files/" + System.currentTimeMillis() + ".jpg")//后缀名需要自行判断修改，如图片格式有：jpg  jpeg png
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                Log.e(TAG, "onResponse: " + result);
//                HeadPortraitResponse headResponse = new Gson().fromJson(result, HeadPortraitResponse.class);
//                final String portraitUri = headResponse.getUrl();
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        changeImg(portraitUri);
//                    }
//                });
//            }
//        });
//    }
//
//    /**
//     * 更换头像
//     * @param portraitUri
//     */
//    private void changeImg(String portraitUri) {
//        OkHttpClient client = OkHttpUtils.getOkHttpClient();
//        String userId = AppConfigUtils.getInstance().getLoginInfo(getActivity()).getObjectId();
//        HeadBean headBean = new HeadBean(userId, portraitUri);
//        final Request request = RequestUtils.requestPOST(headBean, Constant.URL.UPDATEMEHEADPROTRAIT);
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                Log.e(TAG, "onResponse: " + result);
//            }
//        });
//    }
}
